/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.swing;

import java.awt.Image;
import java.io.File;
import java.util.AbstractMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class LRUImageCache extends AbstractMap<File, Image> {

    private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(LRUImageCache.class);

    private class CacheEntry implements Map.Entry<File, Image> {

        private File key;
        private Image value;
        private Long modificationTime;

        public CacheEntry(File key, Image value) {

            this.key = key;
            this.value = value;
            this.modificationTime = key.lastModified();

        }

        public Image getValue() {

            return value;
        }

        public Image setValue(Image value) {

            // Does this cause an infinite loop?
            return put(getKey(), value);

        }

        public File getKey() {

            return key;
        }

        public boolean isValid() {

            Long modificationTime = getKey().lastModified();
            return (modificationTime > 0 && modificationTime.equals(this.modificationTime));
        }
    }

    private Map<File, CacheEntry> impl;

    @SuppressWarnings("serial")
    public LRUImageCache(final int maxSize) {

        LOG.info("Initialising Image Cache with capacity " + maxSize);
        impl = new LinkedHashMap<File, CacheEntry>(maxSize, (float) 0.5, true) {

            @Override
            protected boolean removeEldestEntry(Entry<File, CacheEntry> eldest) {

                boolean b = size() > maxSize;
                if (b) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Removing eldest entry " + eldest.getKey());
                    }
                }
                return b;
            }
        };
    }

    @Override
    public Set<Entry<File, Image>> entrySet() {

        return new HashSet<Entry<File, Image>>(impl.values());
    }

    @Override
    public boolean containsKey(Object key) {

        return impl.containsKey(key);
    }

    @Override
    /**
     * Retrieves an image from the cache. Will return the image if the file exists and has the same modification time.
     * 
     */
    public Image get(Object key) {

        CacheEntry entry = impl.get(key);
        Image result = null;
        if (entry != null) {
            if (entry.isValid()) {
                LOG.debug("Cache hit for " + key);
                result = entry.getValue();
            } else {
                LOG.debug("Cache hit invalid for " + key);
                // Don't know if this is valid in a Map either, might break
                // iterators.
                remove(key);
            }
        } else {
            LOG.debug("Cache miss for " + key);
        }

        return result;
    }

    @Override
    public Image put(File key, Image value) {

        Image result = get(key);
        impl.put(key, new CacheEntry(key, value));
        return result;
    }

    @Override
    public Image remove(Object key) {

        // Don't check validity at remove
        Image result = null;
        CacheEntry entry = impl.remove(key);
        if (entry != null) {
            result = entry.getValue();
        }
        return result;
    }

}
